package com.yxinmiracle.user.controller;

import com.alibaba.fastjson.JSON;
import com.yxinmiracle.core.AbstractCoreController;
import com.yxinmiracle.user.pojo.User;
import com.yxinmiracle.user.service.UserService;
import entity.BCrypt;
import entity.JwtUtil;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/****
 * @Author:YxinMiracle
 * @Description:
 *****/

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController extends AbstractCoreController<User>{

    private UserService  userService;

    @Autowired
    public UserController(UserService  userService) {
        super(userService, User.class);
        this.userService = userService;
    }

    @GetMapping("/test")
    @PreAuthorize(value = "hasAuthority('ROLE_ADMIN')")
    public String show(){
        return "aaa";
    }

    @RequestMapping("/login")
    public Result login(String username, String password, HttpServletResponse response){
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>"+username);
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            return new Result(false, StatusCode.ERROR,"用户名密码不能为空");
        }

        User user = userService.selectByPrimaryKey(username);
        if (user==null){
            return new Result(false, StatusCode.ERROR,"用户名密码不不正常");
        }

        if (!BCrypt.checkpw(password,user.getPassword())){
            return new Result(false, StatusCode.ERROR,"用户名密码不不正常");
        }

        // 生成令牌返回给用户
        Map<String,Object> info = new HashMap<>();
        info.put("username",username);
        info.put("role","ROLE_ADMIN");
        String token = JwtUtil.createJWT(UUID.randomUUID().toString(), JSON.toJSONString(info), null);
        Cookie cookie = new Cookie("Authorization", token);
        cookie.setPath("/");
        response.addCookie(cookie);
        return new Result(true, StatusCode.OK,"登录成功",token);
    }

    @GetMapping("/load/{id}")
    public Result<User> findById(@PathVariable(name = "id")String id){
        User user = userService.selectByPrimaryKey(id);
        return new Result<User>(true, StatusCode.OK,"查询成功",user);
    }

    @GetMapping("/points/add")
    public Result addPoints(@RequestParam(name="username") String username,
                            @RequestParam(name="points") Integer points){
        Integer count = userService.addPoints(username,points);
        if(count>0){
            return new Result(true, StatusCode.OK, "更新成功");
        }else {
            return new Result(false, StatusCode.ERROR, "更新失败");
        }
    }




    public static void main(String[] args) throws Exception {
        //bcrypt
        String encode = new BCryptPasswordEncoder().encode("123");
        System.out.println(encode);

        //
//        byte[] bytes = Base64.getDecoder().decode("eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9");
//        System.out.println(new String(bytes,"utf-8"));
    }
}
